package Jun13.query;

import Jun13.utils.ESUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;

import java.io.IOException;

public class SearchHighLightDoc {

    public static void main(String[] args) throws IOException {
        RestHighLevelClient rest = ESUtils.getRest();//获取ES对象
        SearchRequest search = new SearchRequest().indices("user");//创建查询对象
        SearchSourceBuilder scb = new SearchSourceBuilder();//创建查询条件构建对象
        search.source(scb.query(QueryBuilders.matchAllQuery()));//以查所有为例
        HighlightBuilder hl = new HighlightBuilder();//创建高亮构造对象
        hl.preTags("<font>");//指定高亮内容的前置标签
        hl.postTags("</font>");//指定高亮内容的后置标签
        hl.field("name");//指定要进行高亮展示的字段
        scb.highlighter(hl);//将高亮对象加入SearchSourceBuilder
        search.source(scb);//将查询条件构建对象加入查询对象
        SearchResponse result = rest.search(search, RequestOptions.DEFAULT);//发送包含有查询条件构造对象的查询对象
        SearchHit[] hits = result.getHits().getHits();//获取查询结果
        for (SearchHit s:hits){
            System.out.println(s);//遍历并输出结果
        }
        rest.close();//关闭
    }
}
